import {urlBase} from "./url";
import {AjaxModel} from "./model/AjaxModel";

declare const wx: any;
declare const weui: any;

export const imageUrl =
    (name, ext = "jpg") => `http://${location.host}/resources/images/${name}.${ext}`;

export const voiceUrl =
    (name, ext = "mp3") => `http://${location.host}/resources/voice/${name}.${ext}`;

export const shortString = (str: string, length: number) => str.length > length ? (str.substring(0, length) + '...') : str;

let body: HTMLBodyElement;
export const getBody = (): HTMLBodyElement => body || (body = document.querySelector("body"));

export const initShare =
    (link: string = null,
     desc: string = null,
     imgUrl: string = null,
     title: string = null) => {
        title = shortString(title || document.title, 24);
        desc = shortString(desc || "", 30);
        imgUrl = imgUrl || imageUrl("logo");

        if (!/^https?:\/\/.*?/ig.test(imgUrl)) {
            imgUrl = urlBase + imgUrl;
        }
    };

export const callPhone = (number: string) => {
    const iframe = document.createElement("iframe");
    iframe.src = `tel:${number}`;
    iframe.style.display = "none";
    document.querySelector("body").appendChild(iframe);
    setTimeout(() => {
        iframe.remove();
    }, 2000)
};


/**
 * 获取指定的URL参数值
 */
export const getParam = (name) => {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.hash.substr(1).match(reg);
    if (r != null) {
        return decodeURIComponent(r[2])
    }
    return null;
};

export const checkLoginStatus = (res: AjaxModel, callback: Function) => {
    if (res.code === 300) {
        //状态码为300需要登录
        weui.alert(res.msg || '您的账号未登录或已掉线，需要进行登录', () => {
            location.hash = '/login'
        })
    } else {
        return callback();
    }
};

const version = '0.0.1';
/*
页面制作：何喜阳，制作时间：2018-11，
微信公众号：hexiyangwx ，
博客：http://hexiyang.cn ，
*/
